
import { getMongo } from "../library/mongodb";

export async function saveDataUniq(doc: any, collectionName: string) {
  const mongoClient = await getMongo();
  const collection = mongoClient.collection(collectionName);
  const hasRecord = await collection.find({ id: doc.id }).toArray();
  if (hasRecord.length > 0)
    return await collection.updateOne({ id: doc.id }, { $set: doc });
  return await collection.insertOne(doc);
}


export async function saveData(doc: any, collectionName: string) {
  const mongoClient = await getMongo();
  const collection = mongoClient.collection(collectionName);
  return await collection.insertOne(doc);
}

export async function findAll(collectionName: string, query?: { [keys: string]: any }) {
  const mongoClient = await getMongo();
  const collection = mongoClient.collection(collectionName);
  return await collection.find(query).toArray();
}

export async function findOne(collectionName: string, query: { [keys: string]: any }) {
  const mongoClient = await getMongo();
  const collection = mongoClient.collection(collectionName);
  return await collection.findOne(query);
}

export async function insertMany(doc:any[],collectionName: string) {
  const mongoClient = await getMongo();
  const collection = mongoClient.collection(collectionName);
  return await collection.insertMany(doc);
}